package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.redis.RedisCache;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.iotData.IotMsgNotifyData;
import com.zzyl.nursing.domain.iotData.IotMsgService;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 设备数据Service业务层处理
 * 
 * @author fan
 * @date 2025-06-09
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceDataPageReqDto 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceDataPageReqDto deviceDataPageReqDto)
    {

        LambdaQueryWrapper<DeviceData> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(deviceDataPageReqDto.getDeviceName())){
            wrapper.like(DeviceData::getDeviceName, deviceDataPageReqDto.getDeviceName());
        }
        if (StringUtils.isNotEmpty(deviceDataPageReqDto.getFunctionId())){
            wrapper.eq(DeviceData::getFunctionId, deviceDataPageReqDto.getFunctionId());
        }
        if (ObjectUtil.isNotEmpty(deviceDataPageReqDto.getStartTime()) && ObjectUtil.isNotEmpty(deviceDataPageReqDto.getEndTime())){
            wrapper.between(DeviceData::getAlarmTime, deviceDataPageReqDto.getStartTime(), deviceDataPageReqDto.getEndTime());
        }
        List<DeviceData> deviceDataList = this.list(wrapper);
        return deviceDataList;

    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 设备数据批量保存
     * @param contentStr 设备数据
     */
    @Override
    @Transactional
    public void deviceDataBatchSave(String contentStr) {
        //  解析设备数据
        JSONObject jsonObject = JSONUtil.parseObj(contentStr);
        String notifyData = jsonObject.getStr("notify_data");
        IotMsgNotifyData iotMsgNotifyData = JSONUtil.toBean(notifyData, IotMsgNotifyData.class);

        //查询是否存在该设备
        Device device = deviceService.getOne(new LambdaQueryWrapper<Device>()
                .eq(Device::getIotId, iotMsgNotifyData.getHeader().getDeviceId()));
        if (ObjectUtil.isEmpty(device)){
            throw new BaseException("设备不存在");
        }

        //组装数据
        List<DeviceData> deviceDataList = new ArrayList<>();
        IotMsgService iotMsgService = iotMsgNotifyData.getBody().getServices().get(0);

        //处理上报时间日期
        LocalDateTime eventTime =  LocalDateTimeUtil.parse(iotMsgService.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        Map<String, Object> properties = iotMsgService.getProperties();
        properties.forEach((key, value) -> {
            DeviceData deviceData = new DeviceData();
            BeanUtil.copyProperties(device, deviceData,"id","updateBy","updateTime","createBy","createTime","remark");
            deviceData.setAccessLocation(device.getRemark());
            deviceData.setFunctionId(key);
            deviceData.setDataValue(value.toString());
            deviceData.setAlarmTime(alarmTime);
            deviceDataList.add(deviceData);
        });

        //插入数据库
        saveBatch(deviceDataList);

        //插入redis
        redisCache.setCacheMapValue("iot:device_last_data",device.getIotId(),JSONUtil.toJsonStr(deviceDataList));

    }
}
